package cn.xinfei.xdecision.engine.runner.executor;

import cn.xinfei.xdecision.engine.runner.executor.strategy.EngineComponentRunner;
import cn.xinfei.xdecision.engine.runner.executor.strategy.EngineNodeRunner;
import cn.xinfei.xdecision.engine.runner.executor.strategy.IEngineRunner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class NodeHandlerContainer implements ApplicationContextAware {

    @Autowired
    private Map<String, IEngineRunner> nodeRunnerMap;

    public IEngineRunner getEngineRunnerNode(String nodeType,String handlerType) {
        IEngineRunner IEngineRunner = NodeHandlerContainer.this.nodeRunnerMap.get(handlerType+nodeType);
        return IEngineRunner;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, EngineNodeRunner> beansWithAnnotation = applicationContext.getBeansOfType(EngineNodeRunner.class);
        beansWithAnnotation.entrySet()
                .forEach(entry -> {
                    String key = entry.getKey();
                    EngineNodeRunner value = entry.getValue();
                    String serviceName = value.getServiceName();
                    nodeRunnerMap.put(serviceName, value);
                });

        Map<String, EngineComponentRunner> beansWithAnnotation2 = applicationContext.getBeansOfType(EngineComponentRunner.class);
        beansWithAnnotation2.entrySet()
                .forEach(entry -> {
                    String key = entry.getKey();
                    EngineComponentRunner value = entry.getValue();
                    String serviceName = value.getServiceName();
                    nodeRunnerMap.put(serviceName, value);
                });
        log.info("---------------------------------");
    }
}
